<template>
  <view class="edit-profile">
    <!-- 背景图 -->
    <view class="background-container">
      <image class="background-image" :src="backgroundImage || '/static/sample2.jpg'" mode="aspectFill" @click="chooseBackground"></image>
      <!-- <view class="change-bg">更换背景</view> -->
    </view>
    
    <!-- 头像 -->
    <view class="avatar-container">
      <image class="avatar-image" :src="avatarImage || '/static/sample1.jpg'" mode="aspectFill" @click="chooseAvatar"></image>
      <!-- <view class="change-avatar">更换头像</view> -->
    </view>

    <!-- 表单内容 -->
    <view class="form-container" style="margin-top: 10px;">
      <view class="form-item">
        <text class="label">昵称</text>
        <input class="input" placeholder="请输入昵称" v-model="nickname"/>
      </view>
      
      <view class="form-item">
        <text class="label">性别</text>
        <picker class="picker" mode="selector" :range="genders" @change="onGenderChange">
          <view class="picker-text">{{genders[genderIndex]}}</view>
        </picker>
      </view>
      
      <view class="form-item">
        <text class="label">生日</text>
        <picker class="picker" mode="date" @change="onBirthdayChange">
          <view class="picker-text">{{birthday || '请选择生日'}}</view>
        </picker>
      </view>
      
      <view class="form-item">
        <text class="label">个人简介</text>
        <textarea class="textarea" placeholder="介绍一下自己" v-model="bio"></textarea>
      </view>
      
      <button class="save-btn" @click="saveProfile">保存修改</button>
    </view>
  </view>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { http, baseUrl } from '../../../utils/request'

const avatarImage =ref('')
const backgroundImage =ref('')
const nickname = ref('')
const genderIndex = ref(0)
const genders = ref(['男', '女', '保密'])
const birthday = ref('')
const bio = ref('')

onMounted(async()=>{
	await http.get('/users/validate-token')
	try {
		const userId = uni.getStorageSync('userId');
		if(!userId){
			console.log("未查到用户ID");
			return;
		}
		const user_info = await http.get('/users/info', {userId});
		console.log(user_info);
		
		// 绑定用户信息到表单
		avatarImage.value = user_info.avatarUrl || '';
		backgroundImage.value = user_info.backgroundUrl || '';
		nickname.value = user_info.nickName || '';
		bio.value = user_info.bio || '';
		birthday.value = user_info.birthday || '';
    genderIndex.value = user_info.gender==='男' ? 0 : (user_info.gender==='女' ? 1 :2 );
		
	} catch (error) {
		console.error("获取用户信息失败:"+error);
	}
	
})
const chooseAvatar = async () => {
  try {
    const res = await uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album']
    })
    avatarImage.value = res.tempFilePaths[0]
  } catch (err) {
    console.log('选择头像失败', err)
  }
}
const chooseBackground = async () => {
  try {
    const res = await uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album']
    })
    backgroundImage.value = res.tempFilePaths[0]
  } catch (err) {
    console.log('选择背景图失败', err)
  }
}
const onGenderChange = (e) => {
  genderIndex.value = e.detail.value
}

const onBirthdayChange = (e) => {
  birthday.value = e.detail.value
}


const saveProfile = async () => {
	try{
		const header = {
			'Content-Type': 'multipart/form-data',
			'Authorization' : `Bearer `+uni.getStorageSync('token')
		}
		var avatarUrl = avatarImage.value
		var backgroundUrl = backgroundImage.value
		try {
		  const uploadTask1 = await uni.uploadFile({
		      url: baseUrl + '/posts/image', // 专门的图片上传接口
		      filePath: avatarImage.value,
		      name: 'image', // 根据后端要求调整字段名
		      header
		  });
		  avatarUrl = JSON.parse(uploadTask1.data).data;
		} catch (err) {
		  console.log('上传头像失败', err)
		}
		
		try {
		  const uploadTask2 = await uni.uploadFile({
		      url: baseUrl + '/posts/image', // 专门的图片上传接口
		      filePath: backgroundImage.value,
		      name: 'image', // 根据后端要求调整字段名
		      header
		  });
		  backgroundUrl = JSON.parse(uploadTask2.data).data;
		} catch (err) {
		  console.log('上传背景图失败', err)
		}
		
    // 准备提交数据
    const formData = {
      avatarUrl,
      backgroundUrl,
      nickName: nickname.value,
      gender: genders.value[genderIndex.value],
      birthday: birthday.value,
      bio: bio.value
    }

    // 提交到API
    await http.post('/users/edit', formData);

    uni.showToast({
      title: '保存成功',
      icon: 'success'
    });
    setTimeout(()=>{uni.navigateBack()}, 300);
  } catch (error) {
    console.error('保存失败:', error);
    uni.showToast({
      title: '保存失败',
      icon: 'error'
    })
  }
}
</script>

<style>
.background-container {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.background-image {
  width: 100%;
  height: 100%;
}

.change-bg {
  position: absolute;
  right: 15px;
  bottom: 15px;
  background: rgba(0,0,0,0.5);
  color: white;
  padding: 5px 10px;
  border-radius: 15px;
  font-size: 12px;
}

.avatar-container {
  position: absolute;
  top: 60px;
  left: 20px;
  width: 80px;
  height: 80px;
  border-radius: 50%;
  border: 3px solid white;
  overflow: visible;
  z-index: 1000;
}

.avatar-image {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.change-avatar {
  position: absolute;
  left: 30px;
  bottom: 15px;
  background: rgba(0,0,0,0.5);
  color: white;
  padding: 5px 10px;
  border-radius: 15px;
  font-size: 12px;
}
.edit-profile {
  background-color: #f8f8f8;
  min-height: 100vh;
  padding-top: 0px;
}

.custom-navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #ffffff;
  box-shadow: 0 2px 4px rgba(0,0,0,0.08);
  z-index: 999;
}

.form-container {
  padding: 20px;
}

.form-item {
  background: #fff;
  padding: 15px;
  margin-bottom: 15px;
  border-radius: 8px;
}

.label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.input, .picker, .textarea {
  width: 100%;
  padding: 10px 0;
  font-size: 16px;
}

.picker-text {
  padding: 10px 0;
}

.textarea {
  height: 100px;
  border: 1px solid #eee;
  padding: 10px;
  border-radius: 4px;
}

.save-btn {
  margin-top: 30px;
  background-color: #007AFF;
  color: white;
  border-radius: 8px;
  padding: 12px;
  font-size: 16px;
}
</style>
